package com.cloudptt.wp;


import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;

import com.cloudptt.api.comm.CheckData;
import com.cloudptt.api.comm.FileOperation;
import com.cloudptt.api.comm.IniFileParser;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.UpdateUiListener;
import com.cloudptt.api.product.adapter.ISingleHalfCallNotify;
import com.cloudptt.api.product.func.message.NotifyListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.AddrOperator;
import com.cloudptt.api.product.operator.CallOperator;
import com.cloudptt.wp.ui.call.CallActivity;
import com.cloudptt.wp.ui.call.FloorDlg;
import com.cloudptt.wp.ui.main.MainActivity;
import com.cloudptt.wp.ui.menu.PersonAddressActivity;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.ServerInfo;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.GroupInfo;
import com.mcptt.http.operator.IHttpAddrOpCb;

import java.io.File;

//import com.cloudptt.wp.ui.call.CallActivity;

/**
 * 继承Application
 *
 * @author admin
 *
 */
public class SysApplication extends Application implements NotifyListener, ISingleHalfCallNotify
{
	public static final String APPID = "appid=1442820561";//0x55ffb1d1
	public static String THIS_FILE = "SysApplication";
	public static String APP_KEY = "ptt/wuping";

	private Product product = null;
	private IHttpAddrOpCb addrUptListener = null;
	private UpdateUiListener updateUiListener = null;
//	private ProgressDialog mDownloadDialog;
	private SysConfig config = null;

	public static boolean isFristLogin = false;
	@Override
	public void onCreate()
	{
		super.onCreate();
		Log.d(THIS_FILE,"onCreate");
		creatProduct();
	}


	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
		Log.d(THIS_FILE,"onLowMemory");
	}
	public void onTrimMemory(int level)
	{
		super.onTrimMemory(level);
		Log.d(THIS_FILE,"onTrimMemory level = " + level);


	};

	@Override
	public void onTerminate()
	{
		Log.d(THIS_FILE,  "onTerminate");

		if(product != null){
			product.doExit();
			product = null;
		}
//		SysApplication app = ((SysApplication) getApplicationContext());
//		Product product = app.getProduct();
//		if(product != null)
//		{
//			product.doExit();
//		}
//
//		ScreenManager.getScreenManager().popAllActivity();
//		SystemClock.sleep(2000);
//		System.exit(0);

		super.onTerminate();
	}


	public static final String GROUP_CREATE_RESULT_ACTION = "org.hytera.create_group_ACTION";
	public void creatProduct()
	{
		Log.d(THIS_FILE,  "creatProduct");
		if(product == null){
			this.product = new Product(this,ProductConst.ProductType_XAPP,ProductConst.Product_Simple,R.drawable.ptticon, MainActivity.class);
		}
		this.product.setLogStatus();
		this.product.setPCallClass(CallActivity.class);
		this.product.setNotifyListener(this);
		this.product.getGCallEventAdapter().setSingleHalfCallNotify(this);
		this.config = product.getSysConfig();
		String ipStr = getCurSvrIp();
		Log.debug(this.getClass(), " ipStr is " + ipStr);
		if(ipStr != null) {
			this.config.setServerInfo(ipStr, 10001);
		}
		String devId = getDeviceId();//"86541+8050394673";//"865865050002633";//
		Log.d(THIS_FILE,  "NEW getDeviceId id = " + devId);
		if(devId != null) {
			config.setDevIdBeforLogin(devId);
//			config.setTestUserInfoBeforLogin("10002","123456");
		}

		Intent createintent = new Intent(GROUP_CREATE_RESULT_ACTION);
		sendBroadcast(createintent);
	}

	private String getDeviceId()
	{
		Log.d(THIS_FILE,  "getDeviceId SDK_INT = " + Build.VERSION.SDK_INT);
		 TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//        if (Build.VERSION.SDK_INT >= 29) {
//            return "999999999999999"; //Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//			Log.d(THIS_FILE,  "getDeviceId manager.getImei() = " + manager.getImei());
//            return manager.getImei();
//        } else
		{
			Log.d(THIS_FILE,  "getDeviceId manager.getDeviceId() = " + manager.getDeviceId());
            return manager.getDeviceId();
        }
//		return id;
	}


	private String getCurSvrIp()
	{
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			String filePath = FileOperation.getConfigFilePath();
			File file = new File(filePath);
			if(!file.exists())
			{
				return null;
			}
			// 获得存储卡的路径
			Log.debug(this.getClass(), " filePath is " + filePath);
			IniFileParser parser = new IniFileParser(this.getApplicationContext());
			parser.readFrom(filePath);
			if(parser.getStringKey("tx") != null && parser.getStringKey("rx") != null) {
				float txLevel = CheckData.parseFloat(parser.getStringKey("tx"));
				float rxLevel = CheckData.parseFloat(parser.getStringKey("rx"));
				if(txLevel > 1.99)
				{
					txLevel = (float)1.99;
				}
				if(rxLevel > 1.99)
				{
					rxLevel = (float)1.99;
				}
				Log.debug(this.getClass(), " txLevel = " + txLevel + " rxLevel = " + rxLevel);
				this.config.setVoiceLevel(txLevel,rxLevel);
			}
			if(parser.getStringKey("showApp") != null) {
				String val = parser.getStringKey("showApp");
				boolean isShow = CheckData.parseBoolean(val);
				this.config.setShowApp(isShow);
			}
			if(parser.getStringKey("svr") != null) {
				return parser.getStringKey("svr");
			}

			Log.debug(this.getClass(), " ServerInfo.Default_Svr_Ip is " + ServerInfo.Default_Svr_Ip);
		}
		return null;
	}

	public Product getProduct() {
		return product;
	}

	public void showWarning(String msg){
		Intent intent = new Intent();
		intent.setAction("android.intent.action.WARNING");
		intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		intent.putExtra("msg", msg);
		startActivity(intent);
	}


	@Override
	public void receiveNotify(String msg) {
		// TODO Auto-generated method stub
		Log.d(THIS_FILE, "BlackList application msg = "+msg);
		showWarning(msg);
	}

    @Override
    public void receiveAddrUptMsg()
    {
        Log.d(THIS_FILE, "receiveAddrUptMsg");
        if(product != null
                && product.getOperator(ProductConst.Func_Addr) != null)
        {
            SysConfig config = product.getSysConfig();
            AddrOperator addrOperator = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
            addrOperator.loadAddress(config,addrUptListener);
        }
    }
	@Override
	public void receiveOnlineMsg()
	{
		Log.d(THIS_FILE, "receiveOnlineMsg");
		if(product != null
				&& product.getOperator(ProductConst.Func_Addr) != null)
		{
			SysConfig config = product.getSysConfig();
			AddrOperator addrOperator = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
			addrOperator.loadAddress(config,addrUptListener);
		}
	}
	@Override
	public void receiveSos(String num)
	{
		if(product != null
				&& product.getOperator(ProductConst.Func_Addr) != null)
		{
			GroupInfo info = product.getSysConfig().getSosGroupInfo();
			if(info == null)
			{
				return;
			}
			if(!product.getGCallEventAdapter().isRecvSos()) {
				CallOperator operator = (CallOperator) product.getSuperCallOperator().getCallOperator();
				operator.ringOrStopSos();
			}
			if(info !=null)
			{
				product.getGCallEventAdapter().setRecvSos(true);
				AddrInfo oldDefaultGroupInfo = product.getDefaultGroupInfo();//.getCurGroupInfo();
				Log.d(THIS_FILE, "onSOS oldDefaultGroupInfo = " + oldDefaultGroupInfo);
				if(oldDefaultGroupInfo != null
						&& !oldDefaultGroupInfo.isSameOne(info))
				{
					product.setOldDefaultGroupInfo(oldDefaultGroupInfo);
				}

				product.setDefaultGroupInfo(info);
				product.setCurGroupInfo(null);

				if (updateUiListener != null) {
					AddrInfo addrInfo = product.getUserInfoByNum(num);
					if(addrInfo != null) {
						updateUiListener.UpdateUi(UpdateUiListener.Type_SosStr, addrInfo.getName());
					}
				}
			}
		}
	}



	public void setAddrUptListener(IHttpAddrOpCb addrUptListener) {
		this.addrUptListener = addrUptListener;
	}
	public void setUpdateUiListener(UpdateUiListener updateListener) {
		this.updateUiListener = updateListener;
	}

	@Override
	public void showSingleHalfCallDlg(AddrInfo addrInfo) {
		Message msg = mHandler.obtainMessage(1,addrInfo.getDscp());
		msg.sendToTarget();
	}
	private Handler mHandler = new Handler(Looper.getMainLooper()) {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(updateUiListener != null)
			{
				updateUiListener.showHalfCallDlg(msg.obj.toString());
			}
		}
	};

//	public void showUploadDialog(Context ctx,File file,long len)
//	{
//
//		mDownloadDialog = new ProgressDialog(ctx);
//
//		mDownloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//		mDownloadDialog.setIcon(android.R.drawable.progress_indeterminate_horizontal);
//		String str = Resource.getString("soft_updating");
//		mDownloadDialog.setMessage(str);
//		mDownloadDialog.setCancelable(false);
//		mDownloadDialog.show();
//
//		uploadFile(file,len);
//	}
//	private void uploadFile(File file, long len)
//	{
//		Log.d(THIS_FILE, "uploadFile file = " + file);
//		if(!file.exists())
//		{
//			Log.d(THIS_FILE, "uploadFile file no exists pic = " + file);
//			Toast.makeText(this, "file is no exist " + file, Toast.LENGTH_SHORT).show();
//			return;
//		}
//		SysApplication app = ((SysApplication) getApplicationContext());
//		Product product = app.getProduct();
//		if(product != null)
//		{
//			ServerInfo info = product.getSysConfig().getFileServerInfo();
//			String svrIp = info.getIp();
//			MsgOperator operator = (MsgOperator)product.getOperator(ProductConst.Func_Msg);
//			String url = "http://" + svrIp + ":10016/common/uploadLogFile";
//			operator.uploadFile(url, file, len,this,this,"");
//		}
//	}
//	@Override
//	public void onOpResult(int id, boolean isSuc, int cause, String str) {
//		String result = " failed";
//		if(isSuc)
//		{
//			result = " successful";
//		}
//		CommDlg.showToast(this,"file upload " + result);
//	}
//
//	@Override
//	public void onProgress(long bytesRead, long contentLength, boolean done, String remoteFilePath, long len) {
//		Log.debug(getClass(), "bytesRead:" + bytesRead);
//		Log.debug(getClass(), "contentLength:" + contentLength);
//		Log.debug(getClass(), "done:" + done);
//		if(done)
//		{
//			//onSendMsg(SessionInfo.Msgtype_File,remoteFilePath,len);
//			mDownloadDialog.dismiss();
//			CommDlg.showToast(this,"file upload successful");
//		}
//		else
//		{
//			float value = ((float)bytesRead)/contentLength;
//			Log.debug(getClass(), "onProgress value:" + value);
//			int progress = (int)(value * 100);
//			Log.debug(getClass(), "onProgress progress:" + progress);
//			mDownloadDialog.setProgress(progress);
//		}
//	}
}
